import Vue from 'vue'
import router from '@/router'
import store from '@/store'
import * as doms from './dom'
import qs from 'qs'
import { Message } from 'element-ui'
import Axios from './axios'

var utils = {
  /**
   * 发送流量统计请求
   */
  sentRecord(name) {
    Vue.prototype
      .$ajax({
        url: Vue.prototype.$ajax.setUrl('sys/sysOperateRecord'),
        method: 'post',
        data: Vue.prototype.$ajax.setData({
          closeTm: '',
          openPage: name,
          openTm: utils.formatDateTime(new Date()),
          operatorBrowser: utils.myBrowser()
        })
      })
      .then(({ data }) => {
        if (data && data.code === '0') {
          // 成功后执行的操作，返回数据在data.data中
        } else {
          // 失败后执行的操作
        }
      })
  },

  /**
   * 判断浏览器类型
   */
  myBrowser() {
    var userAgent = navigator.userAgent //取得浏览器的userAgent字符串
    var isOpera = userAgent.indexOf('Opera') > -1
    if (isOpera) {
      return 'Opera'
    } //判断是否Opera浏览器
    if (userAgent.indexOf('Firefox') > -1) {
      return 'FF'
    } //判断是否Firefox浏览器
    if (userAgent.indexOf('Chrome') > -1) {
      return 'Chrome'
    }
    if (userAgent.indexOf('Safari') > -1) {
      return 'Safari'
    } //判断是否Safari浏览器
    if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
      return 'IE'
    } //判断是否IE浏览器
  },

  /**
   * 系统登出
   */
  sysOut(to) {
    if (to) router.push({ name: 'login', query: { redirect: to.fullPath } })
    else router.push({ name: 'login' })
    // if (process.env.NODE_ENV !== 'production') router.push({ name: 'login' })
    // else location.href = process.env.VUE_APP_SSO_OUTURL
  },

  /**
   * 修改vue跳转为新增窗口
   * route: 当前路由信息
   * query: vue query参数
   * params: vue params参数
   */
  blank(name, argument) {
    if (argument && argument.newpage) {
      let Obj = {}
      if (name) {
        let routeName = ''
        let allRoutes = router.options.routes
        allRoutes.map(v => {
          if (v.name === 'main') {
            v.children.map(item => {
              if (item.name === name) routeName = item.name
            })
          }
        })
        Obj.name = routeName
      }
      if (argument && argument.query) Obj.query = argument.query
      if (argument && argument.params) Obj.params = argument.params
      let routeUrl = router.resolve(Obj)
      window.open(routeUrl.href, '_blank')
    } else {
      let Obj = { name }
      if (argument && argument.query) Obj.query = argument.query
      if (argument && argument.params) Obj.params = argument.params
      router.push(Obj)
    }
  },

  /**
   * 日期格式化
   */
  formatDateTime(date) {
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    var d = date.getDate()
    d = d < 10 ? '0' + d : d
    var h = date.getHours()
    h = h < 10 ? '0' + h : h
    var minute = date.getMinutes()
    minute = minute < 10 ? '0' + minute : minute
    var second = date.getSeconds()
    second = second < 10 ? '0' + second : second
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
  },

  /**
   * 是否有权限
   * @param {*} key
   */
  isAuth(key) {
    if (process.env.NODE_ENV !== 'production') {
      return true
    }
    let list = key.split(',')
    let bool = true
    for (var i = 0; i < list.length; i++) {
      if (store.state.user.permList.indexOf(list[i]) === -1) {
        bool = false
        break
      }
    }
    return bool
  },

  /**
   * 获取字典
   * @param {*} type
   */
  getDict(type) {
    if (type.indexOf('$') === 0) {
      return store.state.user.dictListPrivate[type] || {}
    }
    return store.state.user.dictList[type] || {}
  },

  /**
   * 获取字典取值类型
   * @param {*} type
   */
  getDictDb(type) {
    return store.state.user.dictDbList[type] || {}
  },

  /**
   * 获取字典数组
   * @param {*} type
   */
  getDictList(type) {
    var list = []
    var obj = utils.getDict(type)
    Object.keys(obj).forEach(item => {
      list.push({
        key: parseInt(item),
        value: obj[item]
      })
    })
    return list
  },

  /**
   * 获取图片src
   * @param {*} id
   */
  getImg(id, domain = 'baseUrl') {
    return (
      window.TAG_CONFIG[domain] + 'stg/stgFileUpload/imageOut/' + id + '?token=' + window.localStorage.getItem('token')
    )
  },

  /**
   * 下载文件
   * @param {*} fileId
   */
  downloadFile(fileId, domain = 'baseUrl') {
    if (!utils.isAuth('stg:stgFileUpload:view')) {
      Message.error('没有进行该操作的权限')
      return
    }
    var download_file = {}
    if (typeof download_file.iframe == 'undefined') {
      var iframe = document.createElement('iframe')
      download_file.iframe = iframe
      document.body.appendChild(download_file.iframe)
    }
    download_file.iframe.src =
      window.TAG_CONFIG[domain] +
      'stg/stgFileUpload/download/' +
      fileId +
      '?token=' +
      window.localStorage.getItem('token')
    download_file.iframe.style.display = 'none'
  },
  /**
   * 自定义下载文件
   * @param {*} url
   * @param {*} params
   */
  downloadCustomFile(url, params, domain = 'baseUrl') {
    if (!utils.isAuth('stg:stgFileUpload:view')) {
      Message.error('没有进行该操作的权限')
      return
    }
    var download_file = {}
    if (typeof download_file.iframe == 'undefined') {
      var iframe = document.createElement('iframe')
      download_file.iframe = iframe
      document.body.appendChild(download_file.iframe)
    }
    download_file.iframe.src =
      window.TAG_CONFIG[domain] + url + '?token=' + window.localStorage.getItem('token') + '&' + qs.stringify(params)
    download_file.iframe.style.display = 'none'
  },

  /**
   * 清空登录信息
   */
  clearLoginInfo() {
    window.localStorage.removeItem('token')
    store.commit('resetStore')
  },

  /**
   * 对数组进行排序
   * @param {*} data
   * @param {*} mainSort
   * @param {*} minorSort
   */
  sortArray(data = [], mainSort = '', mainDescend, minorSort = '', minorDescend) {
    if (!Array.isArray(data) || !mainSort) return data
    var list = JSON.parse(JSON.stringify(data))
    list.sort((a, b) => {
      let num = 0
      if (mainDescend) {
        // 降序
        num = b[mainSort] - a[mainSort]
      } else {
        // 升序
        num = a[mainSort] - b[mainSort]
      }
      if (minorSort && num === 0) {
        if (minorDescend) {
          // 降序
          num = b[minorSort] - a[minorSort]
        } else {
          // 升序
          num = a[minorSort] - b[minorSort]
        }
      }
      return num
    })
    return list
  },

  /**
   * 将树结构数组转换为树
   * @param {*} data
   * @param {*} config
   */
  arrayToTree(
    data = [],
    {
      id = 'id',
      pid = 'parentId',
      mainSort = '',
      mainDescend = false,
      minorSort = '',
      minorDescend = false,
      children = '_children',
      setParent = '',
      setParentId = ''
    } = {}
  ) {
    if (!Array.isArray(data)) return data
    var list = utils.sortArray(JSON.parse(JSON.stringify(data)), mainSort, mainDescend, minorSort, minorDescend)
    var res = []
    var temp = {}
    for (var i = 0; i < list.length; i++) {
      temp[list[i][id]] = list[i]
    }
    for (var k = 0; k < list.length; k++) {
      if (temp[list[k][pid]] && list[k][id] !== list[k][pid]) {
        if (!temp[list[k][pid]][children]) {
          temp[list[k][pid]][children] = []
        }
        temp[list[k][pid]][children].push(list[k])
        if (setParent && setParentId) {
          list[k][setParent] = temp[list[k][pid]][setParentId]
        }
      } else {
        res.push(list[k])
      }
    }
    return res
  },

  /**
   * 将树转为数组
   * @param {*} data
   * @param {*} config
   */
  treeToArray(data = [], { parent = null, expand = true, show = true, children = '_children' } = {}) {
    if (!Array.isArray(data)) return data
    var list = JSON.parse(JSON.stringify(data))
    let tmp = []
    list.forEach(item => {
      item._show = show
      item._expand = expand
      item._parent = parent
      tmp.push(item)
      if (item[children] && item[children].length > 0) {
        const res = utils.treeToArray(item[children], { parent: item, expand, show, children })
        tmp = tmp.concat(res)
      }
    })
    return tmp
  },

  /**
   * 比较两个数组是否相等
   * @param {*} arr1
   * @param {*} arr2
   */
  compareArray(arr1, arr2) {
    if (arr1.length !== arr2.length) return false
    arr1 = arr1.sort()
    arr2 = arr2.sort()
    let len = arr1.length
    for (let i = 0; i < len; i++) {
      // 对象
      if (typeof arr1[i] === 'object') {
        return utils.compareObject(arr1[i], arr2[i])
      } else {
        if (arr1[i] !== arr2[i]) return false
      }
    }
    return true
  },

  /**
   * 比较两个对象是否相等(只比较内容)
   * @param {*} obj1
   * @param {*} obj2
   */
  compareObject(obj1, obj2) {
    var aProps = Object.keys(obj1)
    var bProps = Object.keys(obj2)
    if (aProps.length != bProps.length) return false
    for (let j = 0; j < aProps.length; j++) {
      var propName = aProps[j]
      var propA = obj1[propName]
      var propB = obj2[propName]
      if (!obj2.hasOwnProperty(propName)) return false
      if (propA instanceof Array) {
        if (!utils.compareArray(propA, propB)) return false
      } else if (typeof propA === 'object') {
        if (!utils.compareObject(propA, propB)) return false
      } else if (propA !== propB) {
        return false
      }
    }
    return true
  },

  /**
   * 判断密码强度
   * CharMode 判断字符类型
   * bitTotal计算强度
   */
  CharMode(iN) {
    if (iN >= 48 && iN <= 57)
      //数字
      return 1
    if (iN >= 65 && iN <= 90)
      //大写
      return 2
    if (iN >= 97 && iN <= 122)
      //小写
      return 4
    else return 8
  },

  bitTotal(num) {
    let modes = 0
    for (let i = 0; i < 4; i++) {
      if (num & 1) modes++
      num >>>= 1
    }
    return modes
  },

  checkStrong(password) {
    if (!password) return -1
    if (password.length < 6) return 0 //密码太短，不检测级别
    let Modes = 0
    for (let i = 0; i < password.length; i++) {
      //密码模式
      Modes |= this.CharMode(password.charCodeAt(i))
    }
    return this.bitTotal(Modes)
  },

  /**
   * 将系统现实的额登录名显示为：昵称/登录名
   * user 用户实体
   * arg1 昵称字段名，默认为nname
   * arg2 登录名字段名，默认为loginUname
   */
  sysShowName(user = {}, arg1 = 'nname', arg2 = 'loginUname') {
    return user[arg1] ? user[arg1] + ' / ' + user[arg2] : user[arg2]
  },

  /**
   * 客群、标签计算、标签分析等界面的发布功能
   * tagId 标签id
   * tagNm 标签名称
   * auditType 标签类型，参考store中的字典$audit_type
   * method 请求方式,post表示发布，delete表示取消发布
   * isAggain 是否重新发布
   */
  release(tagId = '', tagNm = '', auditType = '', method = 'post', isAggain) {
    return new Promise((resolve, reject) => {
      Axios({
        url: Axios.setUrl(isAggain ? 'tag/tagAuditCenter/againRelease' : 'tag/tagAuditCenter/add'),
        method: method,
        data: Axios.setData({ tagId, tagNm, auditType })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          resolve(data)
        } else {
          reject(data)
        }
      })
    })
  },

  /**
   * 加密
   * word 要加密的字符串
   * mode 加密算法
   */
  crypto(word, mode = 'MD5') {
    const cryptoJs = require('crypto-js')
    const newWord = cryptoJs[mode](word)
    return newWord.toString(cryptoJs.enc.Hex)
  },

  /* 引入dom工具 */
  ...doms
}

export default utils
